//
//  MyLocalMapView.m
//  FD
//
//  Created by xiaofang wang on 2018/10/30.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  xcode 10.0笔记

#import "MyLocalMapView.h"
#import <GoogleMaps/GoogleMaps.h>
@interface MyLocalMapView()<GMSMapViewDelegate>

{
    BOOL _firstLocationUpdate;
}
/**Google地图*/
@property (nonatomic, strong) GMSMapView *mapView;

@end

@implementation MyLocalMapView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}
- (void)setupView {
    //创建一个定位坐标点
    GMSCameraPosition *camer = [GMSCameraPosition cameraWithLatitude:23.868 longitude:151.2086 zoom:14];
    //大小和view一样大
    _mapView = [GMSMapView mapWithFrame:self.bounds camera:camer];
    _mapView.delegate = self; //设置代理
    _mapView.settings.compassButton = YES; //显示指南针
    _mapView.settings.myLocationButton = YES; //显示定位按钮
    
    //监听GMSMapView 坐标的移动
    [_mapView addObserver:self forKeyPath:@"myLocation" options:(NSKeyValueObservingOptionNew) context:NULL];
    
    
    //添加到self上
    [self addSubview:_mapView];
    
    // Ask for My Location data after the map has already been added to the UI.
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_mapView.myLocationEnabled = YES;
    });
}

- (void)mapView:(GMSMapView *)mapView didTapMyLocation:(CLLocationCoordinate2D)location {
    NSString *msg = [NSString stringWithFormat:@"lat:%f: lng:%f",location.latitude,location.longitude];
    
    FDLog(@"定位点是：%@",msg);
}


//移除监听
- (void)dealloc {
    [_mapView removeObserver:self forKeyPath:@"myLocation" context:NULL];
}

#pragma mark - KVO update
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (!_firstLocationUpdate) {
        // If the first location update has not yet been received, then jump to that location.
        _firstLocationUpdate = YES;
        CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
        _mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:14];
    }
}

@end
